package com.eshop.utils.html;

import cn.hutool.core.util.StrUtil;

public class EscapeUtil
{
    public static final String RE_HTML_MARK = "(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)";
    private static final char[][] TEXT;
    
    public static String escape(final String text) {
        return encode(text);
    }
    
    public static String unescape(final String content) {
        return decode(content);
    }
    
    public static String clean(final String content) {
        return new HTMLFilter().filter(content);
    }
    
    private static String encode(final String text) {
        final int len;
        if (text == null || (len = text.length()) == 0) {
            return "";
        }
        final StringBuilder buffer = new StringBuilder(len + (len >> 2));
        for (int i = 0; i < len; ++i) {
            final char c = text.charAt(i);
            if (c < '@') {
                buffer.append(EscapeUtil.TEXT[c]);
            }
            else {
                buffer.append(c);
            }
        }
        return buffer.toString();
    }
    
    public static String decode(final String content) {
        if (StrUtil.isEmpty((CharSequence)content)) {
            return content;
        }
        final StringBuilder tmp = new StringBuilder(content.length());
        int lastPos = 0;
        int pos = 0;
        while (lastPos < content.length()) {
            pos = content.indexOf("%", lastPos);
            if (pos == lastPos) {
                if (content.charAt(pos + 1) == 'u') {
                    final char ch = (char)Integer.parseInt(content.substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                }
                else {
                    final char ch = (char)Integer.parseInt(content.substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            }
            else if (pos == -1) {
                tmp.append(content.substring(lastPos));
                lastPos = content.length();
            }
            else {
                tmp.append(content.substring(lastPos, pos));
                lastPos = pos;
            }
        }
        return tmp.toString();
    }
    
    public static void main(final String[] args) {
        final String html = "<script>alert(1);</script>";
        System.out.println(clean(html));
        System.out.println(escape(html));
        System.out.println(unescape(html));
    }
    
    static {
        TEXT = new char[64][];
        for (int i = 0; i < 64; ++i) {
            EscapeUtil.TEXT[i] = new char[] { (char)i };
        }
        EscapeUtil.TEXT[39] = "&#039;".toCharArray();
        EscapeUtil.TEXT[34] = "&#34;".toCharArray();
        EscapeUtil.TEXT[38] = "&#38;".toCharArray();
        EscapeUtil.TEXT[60] = "&#60;".toCharArray();
        EscapeUtil.TEXT[62] = "&#62;".toCharArray();
    }
}
